package com.peach.inquiry.imsdk.thread;

import com.peach.inquiry.imsdk.LogUtil;

public class SimpleThread extends Thread {
    private boolean runningFlag; // 运行的状态 默认为false
    private TaskAble task; // 要执行的操作
    private int threadNumber; // 线程的编号
    private ThreadNotify myNotify; // 通知接口

    // 标志runningFlag用以激活线程
    public boolean isRunning() {
        return this.runningFlag;
    }

    public synchronized void setRunning(boolean flag) {
        this.runningFlag = flag; // 设置当前线程为true，表示当前线程已经被占用
        if (flag) {
            this.notifyAll(); // 唤醒其他线程就绪
        }
    }

    public TaskAble getTask() {
        return task;
    }

    public void setTask(TaskAble task) {
        this.task = task;
    }

    // 提示哪个线程工作
    public SimpleThread(int threadNumber, ThreadNotify notify) {
        runningFlag = false;
        this.threadNumber = threadNumber;
        LogUtil.i("Thread " + threadNumber + " started.");
        this.myNotify = notify;
    }

    public synchronized void run() {
        try {
            while (true) {
                // 死循环
                if (!runningFlag) {
                    this.wait(); // 判断标志位是否为true，如果runningFlag为false，等待调度?
                } else {
                    LogUtil.i("线程" + threadNumber + "开始执行任务");
                    Object returnValue = this.task.doTask();

                    if (myNotify != null) {
                        myNotify.notifyResult(returnValue);
                    }
                    sleep(1500);
                    LogUtil.i("线程" + threadNumber + "重新准备...");
                    setRunning(false);
                }
            }
        } catch (InterruptedException e) {
            LogUtil.i("线程 Interrupt");
        }
    }

}
